<!--
 * @Author: wang_sheshe
 * @Date: 2021-05-20 10:43:48
 * @LastEditTime: 2021-07-28 10:17:12
 * @Description: 设备维护提交页
-->
<template>
	<article class="bg_4dbfae tourTaskPage">
		<!-- 头组件 -->
		<van-nav-bar title="登记信息"  left-arrow @click-left="back">
			<!-- <template slot="right">
				<div class="parent-circle">
					<div class="child-circle"></div>
				</div>
            </template> -->
		</van-nav-bar>
		<div class="title-time">
			<span>维护时长：</span>
			<label>{{showTime}}</label>
		</div>
		<van-row class="finish-content">
			<van-field
				class="field-right"
				label="开始时间:" 
				placeholder="请选择" 
				required 
				readonly 
				maxlength="25" 
				:border="false" 
				@click="onClickRightIcon('sTime')"
				v-model="registData.startTime"
			>
				<template slot="right-icon">
					<img :src="icon.time" @click="onClickRightIcon('sTime')" style="width: 21px;"/>
				</template>
			</van-field>
			
            <van-field 
				class="field-right"
				label="结束时间:" 
				placeholder="请选择" 
				required
				readonly 
				maxlength="25" 
				:border="false" 
				@click="onClickRightIcon('eTime')"
				v-model="registData.endTime"
			>
				<template slot="right-icon">
					<img :src="icon.time" @click="onClickRightIcon('eTime')" style="width: 21px;"/>
				</template>
			</van-field>  
			<van-field 
				class="field-right"
				label="维护人员:" 
				maxlength="64"  
                required 
				:border="false" 
				@click="personBtn('maintianList')"
				v-model.trim="maintainPerson"
			>
				<template slot="right-icon">
					<van-image  @click="personBtn('maintianList')" width="20" height="20" :src="icon.selectper" />
				</template>
			</van-field>

			<van-field 
				label="工作人签名:" 
				maxlength="64"  
                required 
				:border="false"
				readonly 
				@click="personBtn('workPersonList')"
				v-model.trim="registData.MAKER"
			>
				<template slot="right-icon">
					<van-image  @click="personBtn('workPersonList')" width="20" height="20" :src="icon.selectper" />
				</template>
			</van-field>
			<van-list>
				<van-cell
				v-for="(item,index) in workPersonList"
				clickable
				:key="index"  
				style="padding: 15px 40px;"           
				>
					<div slot="title" style="display: flex;">
						<div style="display: flex;">
							<span>{{item.userName}}</span>
						</div>
						<van-image v-if="item.signImg" @click="delSignBtn('workPersonList',index)" class="imgSize delSign" width="15" height="15" :src="icon.del" />
						<van-image v-if="item.signImg" @click="signBtn('workPersonList',index)" class="imgSize" width="20" height="20" :src="item.signImg" />
						<van-image v-else class="imgSize" width="20" height="20" @click="signBtn('workPersonList',index)" :src="icon.singn" />
					</div>
				</van-cell>
			</van-list>
			
			<van-field 
				label="负责人签名:"  
				maxlength="300" 
                required 
				:border="false" 
				readonly
				v-model.trim="registData.CHECKER"
				@click="personBtn('mainPersonList')"
			>
				<template slot="right-icon">
					<van-image  @click="personBtn('mainPersonList')" width="20" height="20" :src="icon.selectper" />
				</template>
			</van-field>

			<van-list>
				<van-cell
				v-for="(item,index) in mainPersonList"
				clickable
				:key="index"  
				style="padding: 15px 40px;"           
				>
					<div slot="title" style="display: flex;">
						<div style="display: flex;">
							<span>{{item.userName}}</span>
						</div>
						<van-image v-if="item.signImg" @click="delSignBtn('mainPersonList',index)" class="imgSize delSign" width="15" height="15" :src="icon.del" />
						<van-image v-if="item.signImg" @click="signBtn('mainPersonList',index)" class="imgSize" width="20" height="20" :src="item.signImg" />
						<van-image v-if="!item.signImg" class="imgSize" width="20" height="20" @click="signBtn('mainPersonList',index)" :src="icon.singn" />
					</div>
				</van-cell>
			</van-list>
			<van-row style="padding: 0 15px;" class="font14">结论:</van-row>
			<div style="margin: 15px;border-radius: 5px;">
				<van-field  class="textarea-content" v-model.trim="registData.result" rows="2" autosize type="textarea" maxlength="256"
                    placeholder="请输入结论" show-word-limit />
			</div>
			<van-row style="padding: 0 15px;" class="font14">备注:</van-row>
			<div style="margin: 15px;border-radius: 5px;">
				<van-field class="textarea-content" v-model.trim="registData.remark" rows="2" autosize type="textarea" maxlength="256"
                    placeholder="请输入备注" show-word-limit />
			</div>
			<!-- 维护项列表-->
			<div class="task-list">
				<van-collapse v-model="activeNames">
					<van-collapse-item :name="typeItem.workItemTypeId" v-for="typeItem in selTaskList" :title="typeItem.workItemTypeName" :key="typeItem.workItemTypeId">
						<div slot="title" style="display: flex;">
							<span class="line_green"></span>
							<span>{{ typeItem.workItemTypeName }}</span>
						</div>
						<van-cell
						  v-for="(item,index) in typeItem.workItemList"
						  clickable
						  :key="index"            
						  @click="deviceClickEvent(item)"
						  >
						  <div slot="title">
							  <div style="display: flex;justify-content: space-between;">
								  <span>{{item.workItemName}}</span>
							  </div>
							  <div>
								  <span style="color: #999999;">{{item.requireFinishTime | formate}}</span>
							  </div>
						  </div>
					  	</van-cell>
					</van-collapse-item>
				</van-collapse>
			</div>
		</van-row>
		<van-row class="btn-wrapper bottomButtonPosition" style="text-align: center;">
			<van-button type="default" size="small"  @click="cancel">取消</van-button>
			<van-button type="primary" size="small"  @click="registTask">确定</van-button>
		</van-row>

		<!-- 反馈组件 选择人员-->
		<van-popup class="selSub" round close-on-click-overlay v-model="showPerson" position="bottom" @close="showPerson=false">
			<selPople :userList="userList"
			@comfirmPerson="personConfirm" :single="single"
			@closePersonPage="showPerson=false"></selPople>
		</van-popup>
		
		<!-- 时间类型选择器 -->
		<van-popup round close-on-click-overlay v-model="isDatePicker" position="bottom">
			<van-datetime-picker v-model="currentDate" title="选择日期" 
			:min-date="minDate"
			:formatter="formatter"
  			:max-date="maxDate"
			@confirm="onConfirm" @cancel="isDatePicker=false" type="datetime">
				<template slot="default">
					<van-nav-bar title="登记信息"  left-arrow @click-left="back">
						<template slot="right">
							<div class="parent-circle">
								<div class="child-circle"></div>
							</div>
						</template>
					</van-nav-bar>
				</template>
			</van-datetime-picker>
		</van-popup>
		
		<!-- 签名信息 -->
		<van-popup v-model="showSign" close-icon="rise-pop-close" round
		:style="{height: '900',width: '90%'}">
			<sign-name @closesign="closePerson" @personback="personBack"></sign-name>
		</van-popup>
		<!-- pop end -->
	</article>
</template>

<script type="text/javascript">
	import { Tabbar, TabbarItem ,Tag } from 'vant';
	import {registerMaintainRecord} from '../../api/deviceProfect';
	import {UploadSignPhoto} from '../../api/common';
	import selPople  from "@/components/SelPeople.vue"
	import SignName from './SignName.vue';
	import Util from "@/utils/util"
	export default {
		name: 'protectFinish',
		components: {
			SignName,
			selPople
		},
		props:{
			selTaskList: {
				type: Array,
				default: function() {
					return []
				}
			},
		},
		data() {
			return {
				finished:true,
				loading:false,
                registData:{
					startTime: "",//开始时间
					endTime: "",//结束时间
					MAKER: "",
					CHECKER: "",
					remark: "",//备注
					result: "合格",//结论
				},
				single:false,//人员true单选 false多选
				timeType: "",
                isDatePicker:false,//日期显示开关
				currentDate: new Date(),
				activeNames: [],
				userList: [],
				//工作人员列表
				workPersonList: [], 
				//负责人员列表
				mainPersonList: [],
				//维护人员列表
				maintainerList: [],
				showSign:false,//签名开关
				showPerson:false,//人员选择开关
				personType: "",//区分 负责人 工作人员
				arrIndex: "",//数组下标
				icon: {
					"time": require("@assets/img/mainIndex/time.png"),
					"selectper": require("@assets/img/mainIndex/selectper.png"),
					"signName":require('../../../../assets/img/mainIndex/singn.png'),
					"singn":require('../../../../assets/img/mainIndex/singn.png'),
					"del":require('../../../../assets/cancel.png'),
				},
				maintainPerson: "",
				userInfo:{},
				minDate: new Date(new Date().getFullYear()-2,new Date().getMonth()+1,new Date().getDay()),
				maxDate: new Date(new Date().getFullYear()+2,new Date().getMonth()+1,new Date().getDay())
			}
		},
		computed: {
			showTime() {
				var showT ="0时0分";
				if(this.registData.startTime && this.registData.endTime) {
					var start = new Date(this.registData.startTime).getTime();
					var end = new Date(this.registData.endTime).getTime();
					var total = (end -start)/1000;
					if(end > start) {
						var hour = parseInt(total/(60*60));
						var min =  ((total - hour*60*60)/60);
						
					}
					showT = (hour? hour+"时":"") + (min? min+"分":"");
					showT ? showT: "0分";
				}
				return showT;
			}
		},
		methods: {
			//日期格式
			formatter(type, val) {
				if (type === 'year') {
					return val + '年';
				}
				if (type === 'month') {
					return val + '月';
				}
				if (type === 'day') {
					return val + '日';
				}
				if (type === 'hour') {
					return val + '时';
				}
				if (type === 'minute') {
					return val + '分';
				}
				return val;
			},
			//确认按钮
			confirm(){
				this.$emit("confirm");
			},
			//取消
			cancel() {
				this.$emit("cancel")
			},
            onConfirm(val){
				this.isDatePicker = false;
				if(this.timeType == 'sTime') {
					this.registData.startTime = Util.DateUtil.getFormatDateByLong(val,'yyyy-MM-dd hh:mm')
				}else{
					this.registData.endTime = Util.DateUtil.getFormatDateByLong(val,'yyyy-MM-dd hh:mm')
				}
			},
			
			//签名人员回调
			personBack(signImg) {
				this.showSign = false;
				if(this.personType == 'workPersonList') {
					this.workPersonList[this.arrIndex]['signImg'] = signImg;
				}else{
					this.mainPersonList[this.arrIndex]['signImg'] = signImg;
				}
			},
			//关闭签名组件
			closePerson() {
				this.showSign = false;
			},
			//选择时间
            onClickRightIcon(data){
				this.timeType = data;
                this.isDatePicker=true;
			},
			/**
			 * 返回
			 */
			 back(){
				this.$emit("cancel");
			},
			/**
			* @description: 显示人员
			* @param {*}
			* @return {*}
			*/
			personBtn(val){
				this.showPerson=true;
				this.personType = val;
				if(val == "workPersonList") {//工作人员
					this.single = false;
					console.log("this.workPersonList",this.workPersonList)
					this.userList = this.workPersonList;
				}else if(val == "mainPersonList") {//工作负责人
					this.single = true;
					console.log("this.mainPersonList",this.mainPersonList)
					this.userList = this.mainPersonList;
				}else{//维护人员
					this.single = false;
					this.userList = this.maintainerList;
				}
			},
			/**
			* @description: 签名点击事件
			* @param {*}
			* @return {*}
			*/
			signBtn(name,index){
				this.personType = name;
				this.arrIndex = index;
				this.showSign=true;
			},
			/**
			* @description: 删除签名
			* @param {*}
			* @return {*}
			*/
			delSignBtn(name,index) {
				var self = this;
				if(name == "workPersonList") {
					this.workPersonList[index]["signImg"] = "";
					this.workPersonList = JSON.parse(JSON.stringify(this.workPersonList))
				}
				if(name == "mainPersonList") {
					this.mainPersonList[index]["signImg"] = "";
					this.mainPersonList = JSON.parse(JSON.stringify(this.mainPersonList))
				}
			},
			//人员确认页面
			personConfirm(person) {
				console.log("person===",person);
				this.showPerson = false;
				if(person.length == 0) {
					return;
				}
				//工作人员
				if(this.personType == 'workPersonList') {
					//重新添加 保留上次签名信息
					for(var item of person) {
						for(var per of this.workPersonList) {
							if(per.userId == item.userId) {
								item["signImg"] = per.signImg;
								break;
							}else{
								item["signImg"] = "";
							}
						}
					}
					this.workPersonList = JSON.parse(JSON.stringify(person));
				}else if(this.personType == 'mainPersonList'){
				//工作负责人
					for(var item of person) {
						for(var per of this.mainPersonList) {
							if(per.userId == item.userId) {
								item["signImg"] = per.signImg;
								break;
							}else{
								item["signImg"] = "";
							}
						}
					}
					this.mainPersonList = JSON.parse(JSON.stringify(person));
				}else{
					//维护人员
					this.maintainerList = person;
					this.maintainPerson = person.map(item => item.userName).join(",")
				}
			},
			/**
			* @description: 登记维护任务
			* @param {*}
			* @return {*}
			*/
			registTask() {
				if(Util.baseUtil.isEmptyString(this.registData.startTime)) {
					this.$Toast.fail("请选择开始时间!")
					return;
				}
				if(Util.baseUtil.isEmptyString(this.registData.endTime)) {
					this.$Toast.fail("请选择结束时间!")
					return;
				}
				var start = new Date(this.registData.startTime).getTime();
				var end = new Date(this.registData.endTime).getTime();
				if(start > end) {
					this.$Toast.fail("开始时间不能大于结束时间!")
					return;
				}
				if(this.maintainerList.length == 0) {
					this.$Toast.fail("请选择维护人员!")
					return;
				}

				if(this.workPersonList.length == 0) {
					this.$Toast.fail("请选择工作人员!")
					return;
				}
				for(var workPerson  of this.workPersonList) {
					if(!workPerson.signImg) {
						this.$Toast.fail("工作人员未签名!")
						return;
					}
				}
				if(this.mainPersonList.length == 0) {
					this.$Toast.fail("请选择工作负责人员!")
					return;
				}
				for(var mainPerson  of this.mainPersonList) {
					if(!mainPerson.signImg) {
						this.$Toast.fail("负责人员未签名!")
						return;
					}
				}
				if(Util.baseUtil.isEmptyString(this.registData.result)) {
					this.$Toast.fail("请填写结论!")
					return;
				}
				this.uploadSignImg();
			},
			/**
			* @description: 上传签名图片
			* @param {*}
			* @return {*}
			*/
			async uploadSignImg() {
				var imgList =  this.workPersonList.concat(this.mainPersonList);
				console.log(this.workPersonList)
				console.log(this.mainPersonList)
				var signUuid = imgList.map(item => {
					return Util.baseUtil.dataUrlToFile(item.signImg)
				})
				console.log("signUuid",signUuid)
				this.$Toast.loading({
					duration: 0,//展示时长 0不会消失
					message: "签名上传中...",
					forbidClick: true,//是否禁止背景点击
					overlay: true//是否显示背景遮罩层
				})
				try {
                    var signFile = await Promise.all(signUuid);
                    var uuidArr = signFile.map(file => {
						var formData = new FormData; 
						formData.append("file", file) //文件流
                        formData.append("userId",this.userInfo.userId)
                        formData.append("source","1")//1 维护  0 缺陷  2 隐患
                        return UploadSignPhoto(formData)
                    })
					var list = await Promise.all(uuidArr);
					//工作负责人签名
					var personInChargeSign = list[list.length-1].data;
					//工作人员签名id
					var maintainRecordWorkerList = [];
					this.workPersonList.map((item,index) => {
						maintainRecordWorkerList.push({
							workerId: item.userId,
							workerName: item.userName,
							workerSignPic: list[index].data
						})
					})
					this.$Toast.clear();
					this.registerMaintainRecord(maintainRecordWorkerList,personInChargeSign);
                } catch (error) {
                    this.$Toast.clear();
                    console.log("签名上传失败，请稍后再试!") 
                }
			},
			/**
			* @description: 维护信息确认
			* @param {*}
			* @return {*}
			*/
			registerMaintainRecord(workerSign,mainSign) {
				var self = this,startTime="",endTime="",workId=[],maintainPerList=[];
				startTime = new Date(this.registData.startTime).getTime();
				endTime = new Date(this.registData.endTime).getTime();
				this.maintainerList.forEach(item => {
					maintainPerList.push({
						accendantId: item.userId,
						accendantName: item.userName
					})
				})
				this.selTaskList.map(item => {
					if(item.workItemList && item.workItemList.length > 0) {
						var list = item.workItemList.map(work => work.maintainRecordId)
						workId.push(...list);
					}
				})
				var params = {
					maintainRecordIdList: workId,//任务列表
					userId: this.userInfo.userId,//用户id
					roleCode: "",//用户角色
					conclusion: this.registData.result,
					remarks: this.registData.remark,
					startTime: startTime,//开始时间
					endTime: endTime,//结束时间
					maintainerList: maintainPerList,//维护人员
					maintainRecordWorkerList: workerSign, //工作人员签名
					personInChargeSign: mainSign,//工作负责人员签名
					personInChargeName: this.mainPersonList[0].userName,//工作负责人员名称
					personInChargeId:this.mainPersonList[0].userId,//工作负责人员id
				}
				console.log("params",params)
				this.$Toast.loading({
						duration: 0,//展示时长 0不会消失
						message: "维护信息登记中...",
						forbidClick: true,//是否禁止背景点击
						overlay: true//是否显示背景遮罩层
					})
				registerMaintainRecord(params).then(data => {
					self.$Toast.clear();
					if(data.success) {
						self.confirm();
						self.$Toast.success(data.msg)
					}else{
						self.$Toast.fail(data.msg)
					}
				}).catch(err => {
					self.$Toast.fail(err)
				})
			},
			render() {
				this.maintainerList.push({
					userId: this.userInfo.userId,
					userName: this.userInfo.userName
				})
				this.maintainPerson = this.userInfo.userName;//维护人，默认登录人
				this.workPersonList.push({//默认工作人员
					userId: this.userInfo.userId,
					userName: this.userInfo.userName,
					signImg: ""
				})
			}
		},
		filters: {
			formate(val) {
				return Util.DateUtil.getFormatDateByLong(val,'yyyy年MM月dd日')
			}
		},
		mounted() {
			var userInfo = localStorage.getItem("userInfo");
			this.userInfo = JSON.parse(userInfo);
			this.registData.startTime = Util.DateUtil.getFormatDateByLong(new Date().getTime(),'yyyy-MM-dd hh:mm');
			this.render();
		},
		
		created() {
			
		},
		
	}
</script>

<style scoped>
	article {
		display: flex;
		flex-direction: column;
		height: 100vh;
        font-family: 微软雅黑;
		background: #ffffff;
		margin: 0 auto;
		width: 100%;
	}
	.active{
		color: #36BDA6 !important;
		background: #ECF6F4 !important;
	}
    .van-button--default {
        margin-right: 20px !important;
        width: 80px;
    }
    .van-button--primary {
		background-color: #17B49B;
        border: 0.02667rem solid #17B49B;
        color: white;
        width: 138px;
        margin: 0 auto;
    }
	.lineGray{
		height: 8px;
		background-color: #F5F6FA;
		border-radius: 5px;
		margin: 10px;
	}
	.templateDiv{
		display: flex;
		justify-content: space-between;
		padding: 10px 15px;
		font-size: 1.125rem;
    }
    input{
        width: calc(100% - 20px);
        margin: 0px 10px;
        box-sizing: border-box;
		height: 60px;
		border: 1px solid #E2E2E2;
		border-radius: 3px;
    }
	.person-list{
		padding: 10px 40px;display: flex;justify-content: space-between;
		background: #fff;
		font-size: 14px;
	}
	.title-time{
		text-align: center;
		padding: 10px 0px;
		font-size: 14px;
	}
	.finish-content{
		flex: 1; overflow: auto;margin-left: 5px ;margin-right: 5px;background: #fff;
	}
	.textarea-content{
		border: 1px solid #E2E2E2;color:#999;
	}
	.selSub{
		width: 100%;
		height: 100%;
	}
	.task-list{
		overflow: auto;
    	height: 302px;
	}
	.field-right /deep/ .van-field__label{
		width:90px;
	}
	.field-right /deep/ .van-field__control{
		text-align: right;
	}
	.imgSize{
		margin: 0 10px;
	}
	.delSign {
		width: 12px;
		height: 12px;
		position: relative;
		top: -15px;
    	left: 60px;
	}
</style>